#!/bin/bash
# SPDX-FileCopyrightText: © 2017 Siemens AG

# SPDX-License-Identifier: GPL-2.0-only
set -e

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source ${DIR}/before
set -x

if [[ ${1} = "-l" ]]; then
  LOGGING=${2}
  if [[ -z "${LOGGING}" ]]; then
    echo "Please specify a file, where to save the log file to"
    exit 1
  else
    exec &> >(tee -a ${LOGGING})
  fi
fi

${DIR}/install

echo Starting backup at `date`
echo Creating diff of repository at `date`
find /srv/fossology/repository/ -type f -exec du -h {} \; | sort -n | ${DIR}/venv/bin/aws s3 cp --sse AES256 - ${AWS_DIFF_LOCATION}

echo Start database dump at `date`
#### postgresql needs to be restarted for the dump to work
/etc/init.d/postgresql restart
#### these steps are split, because of permissions
su - postgres -c 'pg_dumpall' > ${TMP_FILE}
cp ${TMP_FILE} /srv/fossology/database.txt
echo Done database dump. Starting Upload at `date`

#### sync repository
echo "Uploading and starting backup to S3..."
tar -zcf - /srv/fossology/ | ${DIR}/venv/bin/aws s3 cp --expected-size 200000000000 --sse AES256 - ${AWS_BACKUP_LOCATION}

echo "Uploaded backup as ${FILENAME} to the S3 Bucket ${BUCKET}"
echo Backup script done at `date`
${DIR}/after
rm ${TMP_FILE}
